package com.wenyu.wenyuyuedu.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.bean.BeginBean;
import com.wenyu.wenyuyuedu.bean.ProHideBean;
import com.wenyu.wenyuyuedu.fragment.CircleFragment;
import com.wenyu.wenyuyuedu.fragment.HomePageFragment;
import com.wenyu.wenyuyuedu.fragment.PersonageFragment;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.MainActivityServer;
import com.wenyu.wenyuyuedu.server.ProHideServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.DrawbleUtil;
import com.wenyu.wenyuyuedu.utils.IPAddressUtils;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {
    private static final String TAG1 = "fragment1";
    private static final String TAG2 = "fragment2";
    private static final String TAG3 = "fragment3";
    private static final String TAG4 = "fragment4";
    @InjectView(R.id.fm_container)
    FrameLayout fmContainer;
    @InjectView(R.id.rb_content_fragment_homepage)
    RadioButton rbContentFragmentHomepage;
    @InjectView(R.id.rb_content_fragment_circle)
    RadioButton rbContentFragmentCircle;
    @InjectView(R.id.rb_content_fragment_personage)
    RadioButton rbContentFragmentPersonage;
    @InjectView(R.id.rg_content_fragment)
    RadioGroup rgContentFragment;
    @InjectView(R.id.my_circle)
    ImageView myCircle;
    @InjectView(R.id.tv_personage_count)
    ImageView tvPersonageCount;
    private FragmentManager fragmentManager;
    private int oldCur = 0;
    private int item = 0;
    private Retrofit retrofit;
    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        /*获取用户的ip的地址*/
        String ipAddress = IPAddressUtils.getIPAddress(MainActivity.this);
        System.out.println("LoginActivity:001 " + ipAddress);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        initView();
        StatusBarUtil.setStatusBar(MainActivity.this, R.color.white);
        StatusBarUtil.setStatusBarColor(MainActivity.this,R.color.white);
        rgContentFragment.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            int lastId= 0;
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (lastId == i){
                    return;
                }
                lastId = i;
                initCheck(i);
            }
        });
        check(0);
    }
    android.app.AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    /*显示登陆的dialog*/
    private void showLoginDoalog() {

        ad = new android.app.AlertDialog.Builder(MainActivity.this).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
                ad.dismiss();
            }
        });
    }

    private void initCheck(int checkedId) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        Fragment fragment1 = fm.findFragmentByTag(TAG1);
        Fragment fragment3 = fm.findFragmentByTag(TAG3);
        Fragment fragment2 = fm.findFragmentByTag(TAG2);

        if (fragment1 != null) {
            ft.hide(fragment1);
        }
        if (fragment2 != null) {
            ft.hide(fragment2);
        }
        if (fragment3 != null) {
            ft.hide(fragment3);
        }
        switch (checkedId) {
            case R.id.rb_content_fragment_homepage:
                oldCur = 0;
                if (fragment1 == null) {
                    fragment1 = new HomePageFragment();
                    ft.add(R.id.fm_container, fragment1, TAG1);
                } else {
                    ft.show(fragment1);
                }
                break;
            case R.id.rb_content_fragment_circle:
                oldCur = 1;
                if (fragment2 == null) {
                    fragment2 = new CircleFragment();
                    ft.add(R.id.fm_container, fragment2, TAG2);
                } else {
                    ft.show(fragment2);
                }
                break;
            case R.id.rb_content_fragment_personage:
                oldCur = 2;
                if (fragment3 == null) {
                    fragment3 = new PersonageFragment();
                    ft.add(R.id.fm_container, fragment3,
                            TAG3);
                } else {
                    ft.show(fragment3);
                }
                break;
            default:
                break;
        }
        ft.commit();
        changeStatus(oldCur);
    }

    public void check(int index) {
        switch (index) {
            case 0:
                rgContentFragment.check(R.id.rb_content_fragment_homepage);
                break;
            case 1:
                rgContentFragment.check(R.id.rb_content_fragment_circle);
                break;
            case 2:
                rgContentFragment.check(R.id.rb_content_fragment_personage);
                break;
        }
    }

    /*
    * 初始化布局
    * */
    private void initView() {
        //修改每个drawbleTop的图片的大小
        DrawbleUtil.updateDrawbleTop(this, rbContentFragmentHomepage, R.drawable.bar_homepage_bg, 24);
        DrawbleUtil.updateDrawbleTop(this, rbContentFragmentCircle, R.drawable.bar_circle_bg, 24);
        DrawbleUtil.updateDrawbleTop(this, rbContentFragmentPersonage, R.drawable.bar_personage_bg, 24);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        for (int i = 0; i < rgContentFragment.getChildCount(); i++) {
            RadioButton mTab = (RadioButton) rgContentFragment.getChildAt(i);
            FragmentManager fm = getSupportFragmentManager();
            Fragment fragment = fm.findFragmentByTag((String) mTab.getTag());
            FragmentTransaction ft = fm.beginTransaction();
            if (fragment != null) {
                if (!mTab.isChecked()) {
                    ft.hide(fragment);
                }
            }
            ft.commitAllowingStateLoss();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        RecordTime();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /*退出系统消息的时候*/
    private void queitSystemMessage() {
        String tokenQu = AbSharedUtil.getString(MainActivity.this, SharedConstants.USER_TOKEN);
        Log.e("token",tokenQu);
        if (tokenQu.equals("") || tokenQu == null) {
            return;
        }
        ProHideServer proHideServer = ApiWrapper.getInstance().create(ProHideServer.class);
        Call<ProHideBean> proHide = proHideServer.getProHide(tokenQu, 1);
        proHide.enqueue(new Callback<ProHideBean>() {
            @Override
            public void onResponse(Call<ProHideBean> call, Response<ProHideBean> response) {
                ProHideBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        //操作成功

                    } else if (code == 0) {
                        /*token错误或失效*/
                        //  showLoginDialog();
                        MyToast.showToast(MainActivity.this, "登录超时，请重新登陆！", Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<ProHideBean> call, Throwable t) {
                MyToast.showToast(MainActivity.this, "网络异常，请稍后重试！", Toast.LENGTH_SHORT);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        queitSystemMessage();
    }

    private int type = 1;

    /*用户重新开始进入页面的时候载入的数据*/
    private void RecordTime() {
        String token = AbSharedUtil.getString(MainActivity.this, SharedConstants.USER_TOKEN);
        if (token != null) {
            MainActivityServer mainActivityServer = ApiWrapper.getInstance().create(MainActivityServer.class);
            Call<BeginBean> begin = mainActivityServer.getBegin(token, type);
            begin.enqueue(new Callback<BeginBean>() {
                @Override
                public void onResponse(Call<BeginBean> call, Response<BeginBean> response) {
                    BeginBean body = response.body();
                    if (body != null) {
                        int code = body.getCode();
                        if (code == 1) {
                            BeginBean.InfoBean info = body.getInfo();
                            int circle = info.getCircle();
                            int inform = info.getInform();
                            if (circle == 1) {
                                myCircle.setVisibility(View.VISIBLE);
                            } else if (circle == 0) {
                                myCircle.setVisibility(View.INVISIBLE);
                            }
                            if (inform == 1) {
                                tvPersonageCount.setVisibility(View.VISIBLE);
                            } else if (inform == 0) {
                                tvPersonageCount.setVisibility(View.INVISIBLE);
                            }
                        } else if (code == 3200) {
                            //用户没有登录，
                        } else if (code == 3201) {
                            MyToast.showToast(MainActivity.this, "系统繁忙，请稍后重试!", Toast.LENGTH_SHORT);
                        } else if (code == 3202) {
                            MyToast.showToast(MainActivity.this, "系统繁忙，请稍后重试!", Toast.LENGTH_SHORT);
                        }
                    }
                }

                @Override
                public void onFailure(Call<BeginBean> call, Throwable t) {
                    MyToast.showToast(MainActivity.this, "网络异常，请稍后重试！", Toast.LENGTH_SHORT);
                }
            });
        }

    }

    /**
     * 菜单、返回键响应
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();      //调用双击退出函数
        }
        return false;
    }

    /**
     * 双击退出函数
     */
    private static Boolean isExit = false;

    private void exitBy2Click() {
        Timer tExit = null;
        if (isExit == false) {
            isExit = true; // 准备退出
            MyToast.showToast(this, "再按一次退出程序", Toast.LENGTH_SHORT);
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            finish();
            //System.exit(0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        changeStatus(oldCur);
    }

     void changeStatus(int index){
         switch (index) {
             case 0:
                 StatusBarUtil.setStatusBar(MainActivity.this, R.color.white);
                 break;
             case 1:
                 StatusBarUtil.setStatusBar(MainActivity.this, R.color.white);
                 break;
             case 2:
                 StatusBarUtil.setStatusBar(MainActivity.this, R.color.personage_statue);
                 break;
         }
    }




    /*用于控制小圆点的隐藏*/
    public void setCircleRedHide() {
        myCircle.setVisibility(View.INVISIBLE);
    }

    /*用于我的界面控制小圆点的隐藏*/
    public void setInformRedHide() {
        tvPersonageCount.setVisibility(View.INVISIBLE);
    }
}
